<template>
    <div class="contact-list">
        <div class="contact-editor">
            <h1>通讯录</h1>
            <el-button type="primary" @click="addContactShow">新增联系人</el-button>
            <!--            <el-button type="primary" @click="dialogVisible2 = true , isStatus= 'addGroup'">管理群组</el-button>-->
            <el-button type="danger" @click="deleteContact">删除</el-button>
            <el-dialog title="新增/编辑联系人" :visible.sync="dialogVisible">
                <el-card>
                    <el-form :model="contactForm" :rules="rules" ref="contactForm" label-width="200px">
                        <el-form-item label="联系人姓名" prop="contactName">
                            <el-input v-model="contactForm.contactName" placeholder="请输入联系人姓名"></el-input>
                        </el-form-item>
                        <el-form-item label="联系人备注" prop="remark">
                            <el-input v-model="contactForm.remark" placeholder="请输入联系人备注"></el-input>
                        </el-form-item>
                        <el-form-item label="联系人邮箱" prop="email">
                            <el-input v-model="contactForm.email" placeholder="请输入联系人邮箱"></el-input>
                        </el-form-item>
                        <!--
                                                <el-form-item label="联系人分组" prop="groupId">
                                                    <el-select v-model="contactForm.groupId" placeholder="请选择">
                                                        <el-option
                                                            v-for="item in groups"
                                                            :key="item.groupId"
                                                            :label="item.groupName"
                                                            :value="item.groupId">
                                                        </el-option>
                                                    </el-select>
                                                </el-form-item>
                        -->
                        <div class="contact-editor-footer">
                            <el-button type="primary" @click="addContact" v-if="isStatus==='add'"
                                       style="margin-right: 10vw">添加
                            </el-button>
                            <el-button type="primary" @click="updateContact" v-if="isStatus==='update'"
                                       style="margin-right: 10vw">更新
                            </el-button>
                            <el-button type="primary" @click="dialogVisible = false">取消</el-button>
                        </div>
                    </el-form>
                </el-card>
            </el-dialog>
            <el-dialog title="新增/编辑分组" :visible.sync="dialogVisible2">
                <el-card>
                    <el-form :model="groupForm" ref="groupForm" label-width="200px">
                        <el-form-item label="分组组名" prop="groupName">
                            <el-input v-model="groupForm.groupName" placeholder="请输入分组组名"></el-input>
                        </el-form-item>
                        <el-form-item label="选择操作组名" prop="groupId">
                            <el-select v-model="groupForm.groupId" placeholder="请选择">
                                <el-option
                                    v-for="item in groups"
                                    :key="item.groupId"
                                    :label="item.groupName"
                                    :value="item.groupId">
                                </el-option>
                            </el-select>
                            <div style="color: red">0表示添加分组，非0则修改</div>
                        </el-form-item>

                        <el-button type="primary" @click="addGroupContact"
                                   v-if="isStatus==='addGroup'&&this.groupForm.groupId===0">添加
                        </el-button>
                        <el-button type="primary" @click="updateGroupContact"
                                   v-if="isStatus==='addGroup'&&this.groupForm.groupId!==0">更新
                        </el-button>
                        <el-button type="primary" @click="deleteGroupContact"
                                   v-if="isStatus==='addGroup'&&this.groupForm.groupId!==0">删除
                        </el-button>
                        <el-button type="primary" @click="dialogVisible2 = false">取消</el-button>
                    </el-form>
                </el-card>
            </el-dialog>

            <el-table
                ref="multipleTable"
                :data="formData"
                :cell-style="{'text-align':'center'}"
                :header-cell-style="{'text-align':'center'}"
                tooltip-effect="dark"
                v-model="multipleSelection"
                @selection-change="handleSelectionChange"
                style="width: 100%">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="联系人姓名" prop="contactName"></el-table-column>
                <el-table-column label="联系人备注" prop="remark"></el-table-column>
                <el-table-column label="联系人邮箱" prop="email" width="200"></el-table-column>
                <!--                <el-table-column label="联系人分组" prop="groupName"></el-table-column>-->
                <el-table-column label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button @click="handleEdit(scope.$index, scope.row)" type="primary" size="small">编辑
                        </el-button>
                        <el-button @click="handleDelete(scope.$index, scope.row)" type="danger" size="small">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="contact-list-page">
                <el-pagination v-if="formData.length!==0"
                               @size-change="handleSizeChange"
                               @current-change="handleCurrentChange"
                               :current-page="queryFrom.current"
                               :page-sizes="[10, 30, 50, 100]"
                               :page-size="queryFrom.size"
                               layout="total, sizes, prev, pager, next, jumper"
                               :total="queryFrom.total">
                </el-pagination>
            </div>
        </div>

        <!--
                &lt;!&ndash;右侧联系人分组&ndash;&gt;
                <div class="contact-list-content">
                    <el-input placeholder="搜索联系人" v-model="searchQuery" @input="handleSearch"></el-input>
                    <el-table :data="groups"
                              style="width: 100%" class="hide-header-table"
                              @row-click="handleGroupClick"
                    >

                        <el-table-column prop="groupName" label="分组名称"></el-table-column>

                    </el-table>
                </div>
        -->
    </div>
</template>

<script>
import axios from 'axios';
import validator from "validator";
import {map} from "core-js/internals/array-iteration";
import {mapState} from "vuex";

export default {
    name: 'ContactList',
    inject: ['reload'],
    data() {
        const validateEmail = (rule, value, callback) => {
            const emails = value.split(';');
            const trimmedEmails = emails.map(email => email.trim());
            const uniqueEmails = [...new Set(trimmedEmails)]; // 去除重复项
            // 检查是否有重复的邮箱地址
            if (trimmedEmails.length !== uniqueEmails.length) {
                callback(new Error('邮箱地址中存在重复'));
                return;
            }

            for (const email of emails) {
                if (email.trim() === '') {
                    callback();
                    return;
                }
                if (!validator.isEmail(email.trim())) {
                    callback(new Error('邮箱地址格式不正确'));
                }
            }
            callback();
        };
        return {
            // 列表查询条件
            queryFrom: {
                // userId: null,
                // username: "",
                // name: "",
                // password: "",
                // // role: "student",
                // email: "",
                // phone: "",
                // classId: null,
                // className: ""

                total: 0,
                size: 10,
                current: 1,
                pages: 1,
            },
            formData: [],
            groups: [], // 存储分组信息的数组
            activeNames: [],
            multipleSelection: [],
            contactForm: {
                contactId: '',
                contactName: '',
                email: '',
                remark: '',
                userId: '',
                groupId: 0,

            },
            groupForm: {
                groupId: 0,
                groupName: '',
            },
            contactId: '',
            searchQuery: '',
            dialogVisible: false,
            dialogVisible2: false,
            isStatus: '',

            // selectedContacts: [], // 存储当前选中的分组下的联系人列表
            // groupId:1,
            contacts: [],
            rules: {
                contactName: [
                    {required: true, message: '请输入联系人姓名', trigger: 'blur'},
                    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
                ],
                email: [
                    {required: true, message: '请输入邮箱地址', trigger: 'blur'},
                    {validator: validateEmail, trigger: ['blur', 'change']},
                    // 可以添加其他规则，例如非空验证等
                ]

            }

        };
    },
    created() {
        this.fetchData();
        this.fetchContactsData();
    },
    computed: {
        ...mapState(['user']),
        filteredContacts() {
            if (!this.searchQuery) {
                return this.contacts;
            } else {
                return this.contacts.filter(contact => {
                    return contact.contactName.toLowerCase().includes(this.searchQuery.toLowerCase());
                });
            }
        },
    },
    methods: {
        // 获取分组列表
        async fetchData() {
            this.updateUserInfo("张三")
        },
        // 修改用户信息。
        updateUserInfo(formName) {
            // // console.log("formName================",formName);
            // this.$store.dispatch('updateUserInfo', formName).then(res => {
            //     // console.log("getUserInfo.res", res);
            //     if (res !== undefined && res.resultStatus === true) {
            //         // console.log("this.courseInfo ======>  ", this.courseInfo)
            //         // console.log("updateUserInfo ------- res.resultData ====> ", res.resultData);
            //         // this.classTreeOptions = res.resultData
            //         this.$message.success(res.resultData)
            //         // console.log("this.courseInfo ======>  ", this.courseInfo)
            //     } else if (res !== undefined && res.resultStatus === false) {
            //         this.$message.error(res.errorMessage)
            //     }
            // })
        },
        async fetchData1() {
            try {
                axios.get("").then(response => {
                    console.log(response.data);
                }).catch(error => {
                    console.error(error);
                });

                // // 获取分组列表
                // console.log(this.user);
                // const groupResponse = await axios.get('http://localhost:8989/contact/group?userId=' + this.user.userId);
                // console.log(groupResponse.data);
                // this.groups = groupResponse.data.map(group => ({
                //     ...group,
                //     contacts: [], // 初始化每个分组的联系人列表
                // }));
                //
                // // 遍历分组列表，获取每个分组的联系人
                // for (const group of this.groups) {
                //     const contactResponse = await axios.get('http://localhost:8989/contact/group_list?groupId=' + group.groupId);
                //     group.contacts = contactResponse.data;
                //     console.log("分组内容：【group_list】", group.contacts);
                // }

                console.log(this.groups);
            } catch (error) {
                console.error('Error fetching data:', error);
            }
        },

        // 获取列表数据。
        async fetchContactsData() {
            try {
                const contactResponse = await this.getContactPage()

                // const contactResponse = await axios.get('http://localhost:8989/contact/all_list?userId=' + this.user.userId);
                // console.log("列表数据：【all_list】", contactResponse.data);
                // this.contacts = contactResponse.data.map(contact => ({
                //     ...contact,
                //     groupName: '',
                //     groupId: '',
                // }));
                // for (const contact of this.contacts) {
                //     const groupResponse = await axios.get('http://localhost:8989/contact/group_name?contactId=' + contact.contactId);
                //     contact.groupName = groupResponse.data.groupName;
                //     contact.groupId = groupResponse.data.groupId;
                //     console.log(groupResponse.data)
                //     console.log("联系人分组【group_name】", contact.groupName);
                // }
            } catch (error) {
                console.error('Error fetching data:', error);
            }
        },
        // 获取联系人分页
        async getContactPage() {
            // 获取通讯录列表
            this.$store.dispatch('getContactInfoPage', this.queryFrom).then(res => {
                // console.log("getContactPage =======> res.data =====>", res);
                if (res !== undefined && res.resultStatus === true) {
                    // console.log("res.resultData", res.resultData);
                    // console.log("res.resultData", res.resultData.records);
                    // this.$message.success(res.resultData);
                    this.formData = res.resultData.records
                    this.queryFrom.total= res.resultData.total
                    this.queryFrom.size= res.resultData.size
                    this.queryFrom.current= res.resultData.current
                    this.queryFrom.pages= res.resultData.pages
                } else if (res !== undefined && res.resultStatus === false) {
                    // console.log("res.resultData", res.resultData);
                    this.$message.error(res.errorMessage);
                }
            }).catch(res => {
                this.$message.error("后台出问题啦！程序猿小哥正在紧急修复中！！！");
            });
        },
        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            this.queryFrom.size = val
            this.getContactPage()
        },
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            this.queryFrom.current = val
            this.getContactPage()
        },


        async handleGroupClick(row) {
            const groupId = row.groupId;
            console.log(groupId);
            if (groupId === 0) {
                await this.fetchContactsData();
            } else {
                // const contactResponse = await axios.get('http://localhost:8989/contact/group_list?groupId=' + groupId);
                // this.contacts = contactResponse.data.map(contact => ({
                //     ...contact,
                //     groupName: '',
                // }));
                // for (const contact of this.contacts) {
                //     const groupResponse = await axios.get('http://localhost:8989/contact/group_name?contactId=' + contact.contactId);
                //     contact.groupName = groupResponse.data.groupName;
                //     console.log(groupResponse.data)
                //     console.log("联系人分组：【group_name】", contact.groupName);
                // }
            }


        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        handleHeaderClick(groupId) {
            const index = this.activeNames.indexOf(groupId);
            if (index === -1) {
                this.activeNames.push(groupId);
            } else {
                this.activeNames.splice(index, 1);
            }
        },

        /**
         * 显示添加弹窗。
         */
        addContactShow() {
            this.dialogVisible = true;
            this.isStatus = 'add';
            // 清除残余数据。
            this.contactForm = {
                contactId: '',
                contactName: '',
                email: '',
                remark: '',
                userId: '',
                groupId: 0,

            }
        },
        // 添加联系人。
        addContact() {
            this.$refs.contactForm.validate((valid) => {
                if (valid) {
                    // 校验通过提交。
                    this.dialogVisible = true;
                    console.log("添加表单数据" + this.contactForm.contactName)
                    console.log("添加表单数据" + this.contactForm.groupId)
                    console.log("添加表单数据" + this.contactForm.email)

                    this.$store.dispatch('addContactInfo', this.contactForm).then(res => {
                        // console.log("res.data11111111111111111 =====>", res);
                        if (res !== undefined && res.resultStatus === true) {
                            console.log("res.resultData", res.resultData);
                            this.$message.success(res.resultData);
                            this.getContactPage()
                            this.dialogVisible = false;
                        } else if (res !== undefined && res.resultStatus === false) {
                            // console.log("res.resultData", res.resultData);
                            this.$message.error(res.errorMessage);
                        }
                    }).catch(res => {
                        this.$message.error("后台出问题啦！程序猿小哥正在紧急修复中！！！");
                    });
                }
            });
        },

        // 更新数据。
        updateContact() {
            this.$refs.contactForm.validate((valid) => {
                if (valid) {
                    this.$store.dispatch('updateContactInfo', this.contactForm).then(res => {
                        // console.log("updateContactInfo ==========> res.data =====>", res);
                        if (res !== undefined && res.resultStatus === true) {
                            // console.log("res.resultData", res.resultData);
                            this.$message.success(res.resultData);
                            this.getContactPage()
                            this.reload();
                            this.dialogVisible = false;
                        } else if (res !== undefined && res.resultStatus === false) {
                            // console.log("res.resultData", res.resultData);
                            this.$message.error(res.errorMessage);
                        }
                    }).catch(res => {
                        this.$message.error("后台出问题啦！程序猿小哥正在紧急修复中！！！");
                    });
                }
            })

            // console.log(this.contactForm)
            // axios.post('http://localhost:8989/contact/update?groupId=' + this.contactForm.groupId, this.contactForm).then((response) => {
            //     console.log(response.data)
            //     this.reload();
            //     this.dialogVisible = false;
            // });
        },
        // 删除消息。【批量】
        deleteContact() {
            //复选框删除
            this.$confirm('此操作将删除选中联系人, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // console.log("this.multipleSelection ============> ", this.multipleSelection);
                const contactIds = this.multipleSelection.map(row => row.contactId);
                // console.log("contactIds =======> ", contactIds);
                this.$store.dispatch('deleteContactInfoList', {idList: contactIds}).then(res => {
                    // console.log("updateContactInfo ==========> res.data =====>", res);
                    if (res !== undefined && res.resultStatus === true) {
                        console.log("res.resultData", res.resultData);
                        this.$message.success(res.resultData);
                        // this.getContactPage()
                        this.reload();
                    } else if (res !== undefined && res.resultStatus === false) {
                        // console.log("res.resultData", res.resultData);
                        this.$message.error(res.errorMessage);
                    }
                }).catch(res => {
                    this.$message.error("后台出问题啦！程序猿小哥正在紧急修复中！！！");
                });
                this.multipleSelection = [];
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });

        },

        // 删除数据。【单条】
        handleDelete(index, row) {
            // console.log("row.contactId ========> ", row.contactId)
            this.$confirm('此操作将删除该联系人, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$store.dispatch('deleteContactInfo', row.contactId).then(res => {
                    // console.log("updateContactInfo ==========> res.data =====>", res);
                    if (res !== undefined && res.resultStatus === true) {
                        console.log("res.resultData", res.resultData);
                        this.$message.success(res.resultData);
                        // this.getContactPage()
                        this.reload();
                    } else if (res !== undefined && res.resultStatus === false) {
                        // console.log("res.resultData", res.resultData);
                        this.$message.error(res.errorMessage);
                    }
                }).catch(res => {
                    this.$message.error("后台出问题啦！程序猿小哥正在紧急修复中！！！");
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleEdit(index, row) {
            // console.log("index ", index);
            // console.log("row  ", row);
            this.contactForm = row;
            this.contactId = row.contactId;
            this.dialogVisible = true;
            this.isStatus = 'update';
        },
        handleSearch() {

        },
        // 添加分组。
        addGroupContact() {
            this.groupForm.userId = this.user.userId;
            // axios.post('http://localhost:8989/contact/add_group', this.groupForm).then((response) => {
            //     console.log(response.data)
            //     this.reload();
            //     this.dialogVisible2 = false;
            // });
        },
        // 更新分组
        updateGroupContact() {
            // axios.post('http://localhost:8989/contact/update_group?groupId=' + this.groupForm.groupId, this.groupForm)
            //     .then((response) => {
            //         console.log(response.data)
            //         this.reload();
            //         this.dialogVisible2 = false;
            //     });
        },
        // 删除分组。
        deleteGroupContact() {
            this.$confirm('此操作将删除该分组, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // axios.get('http://localhost:8989/contact/logic_delete_group?groupId=' + this.groupForm.groupId).then((response) => {
                //     console.log(response.data)
                //     this.reload();
                //     this.dialogVisible2 = false;
                // });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 获取信息。【单个】
        getOneContact(contactId) {
            // axios.get('http://localhost:8989/contact/get_contact?contactId=' + contactId)
            //     .then((response) => {
            //         console.log(response.data)
            //         this.contactForm.contactId = response.data.contactId;
            //         this.contactForm.contactName = response.data.contactName;
            //         this.contactForm.email = response.data.email;
            //         this.contactForm.remark = response.data.remark;
            //     })
            // axios.get('http://localhost:8989/contact/group_name?contactId=' + contactId)
            //     .then((response) => {
            //         console.log(response.data)
            //         this.contactForm.groupId = response.data.groupId;
            //     })

        },
        // 获取联系人分组。【单个】
        getOneGroup(groupId) {
            // axios.get('http://localhost:8989/contact/get_group?groupId=' + groupId)
            //     .then((response) => {
            //         console.log(response.data)
            //         this.groupForm.groupId = response.data.groupId;
            //         this.groupForm.groupName = response.data.groupName;
            //     })
        }

    },
    watch: {
        isStatus(newValue) {
            if (newValue === 'update') {
                this.getOneContact(this.contactId);

            } else if (newValue === 'add') {
                this.$refs.contactForm.resetFields();
            } else if (newValue === 'addGroup') {
                this.$refs.groupForm.resetFields();
            }
        },
        'groupForm.groupId'(newVal, oldVal) {
            // 当groupId变化时，这里的代码会被执行
            console.log('groupId changed from', oldVal, 'to', newVal);
            // 你可以在这里添加你需要的逻辑，比如发送请求获取新数据等
            if (newVal !== 0) {
                this.getOneGroup(newVal);
            }
        }
    },
    mounted() {
    },
};
</script>
<style>
.contact-list {
    width: 100%;
    height: 100%;
    display: flex;
}

.contact-list-page {
    text-align: center;
    margin-top: 8vh;
    margin-bottom: 8vh;
}

.contact-editor {
    width: 80%;
    /*margin-top: 5vh;*/

}

.contact-editor-footer {
    text-align: center;
    margin-top: 10vh;
}

.contact-list-content {
    width: 20%;
}

.hide-header-table .el-table__header {
    display: none;
}
</style>